//
//  GWBigRecommendationsView.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/3.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import SnapKit

protocol GWBigRecommendationsViewDelegate {
  func gwBigRecommendationsView(_ view: GWBigRecommendationsView, selectedWithAlbumIdentifier: Int)
}

class GWBigRecommendationsView: UIView {
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var scrollView: UIScrollView!
  @IBOutlet private weak var pageControl: UIPageControl!
  
  // MARK: - Private vars
  
  
  
  // MARK: - Private methods
  
  
  
  // MARK: - Public vars
  
  var delegate: GWBigRecommendationsViewDelegate?
  
  // MARK: - Lifecycle
  
  
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
  func prepare(albums: [Album]) {
    
    scrollView.subviews.forEach {
      if type(of: $0) == GWBigRecommendationItem.self {
        $0.removeFromSuperview()
      }
    }
    
    // scroll
    var prevItem: GWBigRecommendationItem?
    for (index, album) in albums.enumerated() {
      let item: GWBigRecommendationItem = .fromNib()
      item.prepare(album: album)
      item.delegate = self
      scrollView.addSubview(item)
      item.snp.makeConstraints { maker in
        maker.height.equalTo(GWBigRecommendationItem.defaultHeight)
        maker.top.bottom.equalTo(0)
        maker.width.equalTo(scrollView.width - 20)
        
        if index == 0 {
          maker.leading.equalTo(0)
        } else {
          if let prevItem = prevItem {
            maker.leading.equalTo(prevItem.snp.trailing).offset(20)
          }
          if index == albums.count - 1 {
            maker.trailing.equalTo(-30)
          }
        }
      }
      prevItem = item
    }
    // use self as scroll gesture target
    addGestureRecognizer(scrollView.panGestureRecognizer)
    
    // page
    pageControl.numberOfPages = albums.count
  }
}

// MARK: - UIScrollViewDelegate

extension GWBigRecommendationsView: UIScrollViewDelegate {
  func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let page = scrollView.contentOffset.x / scrollView.width
    pageControl.currentPage = Int(page)
  }
}

// MARK: - GWBigRecommendationItemDelegate

extension GWBigRecommendationsView: GWBigRecommendationItemDelegate {
  func gwBigRecommendationItem(_ item: GWBigRecommendationItem, didTappedWithAlbumIdentifier: Int) {
    delegate?.gwBigRecommendationsView(self, selectedWithAlbumIdentifier: didTappedWithAlbumIdentifier)
  }
}
